﻿using AsscerMVCN2512.Models;
using System;
using System.Linq;
using System.Web.Mvc;

namespace AsscerMVCN2512.Controllers
{
    public class OfficeSuppliesController : Controller
    {
        private AssetDBEntities1 db = new AssetDBEntities1();

        public ActionResult Index()
        {
            var currentUser = GetCurrentUser();
            if (currentUser == null)
            {
                return RedirectToAction("LoginProject", "EmpolyInfo");
            }

            bool isAdmin = currentUser.RoleID == 1;
            ViewBag.IsAdmin = isAdmin;
            ViewBag.CurrentUserID = currentUser.EmpolyID;
            ViewBag.CurrentUserName = currentUser.EmpolyName;
            ViewBag.IsAdminStr = isAdmin.ToString().ToLower();

            return View();
        }

        [HttpPost]
        public JsonResult GetOfficeSuppliesList(int page = 1, int limit = 10, string assetName = "", string empolyName = "", int? officeApplyState = null)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser == null)
                {
                    return Json(new { code = 1, msg = "用户未登录" });
                }

                bool isAdmin = currentUser.RoleID == 1;

                // 使用数据库查询
                var query = from record in db.OfficeSuppliesRecordInfo
                            join empoly in db.EmpolyInfo on record.OfficeApplyID equals empoly.EmpolyID
                            join asset in db.AssetInfo on record.AssetID equals asset.AssetID
                            select new
                            {
                                record,
                                empoly,
                                asset
                            };

                // 权限筛选 - 普通员工只能看到自己的记录
                if (!isAdmin)
                {
                    query = query.Where(x => x.record.OfficeApplyID == currentUser.EmpolyID);
                }

                // 条件筛选
                if (!string.IsNullOrEmpty(assetName))
                {
                    query = query.Where(x => x.asset.AssetName.Contains(assetName));
                }

                if (!string.IsNullOrEmpty(empolyName) && isAdmin)
                {
                    query = query.Where(x => x.empoly.EmpolyName.Contains(empolyName));
                }

                if (officeApplyState.HasValue)
                {
                    query = query.Where(x => x.record.OfficeApplyState == officeApplyState.Value);
                }

                // 分页
                int totalCount = query.Count();
                var list = query
                    .OrderByDescending(x => x.record.OfficeApplyDate)
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList()
                    .Select(x => new
                    {
                        id = x.record.OfficeID,
                        AssetName = x.asset.AssetName,
                        OfficeApplyNum = x.record.OfficeApplyNum,
                        OfficeApplyState = x.record.OfficeApplyState,
                        OfficeApplyDate = x.record.OfficeApplyDate,
                        OfficeReceiveNum = x.record.OfficeReceiveNum ?? 0,
                        OfficeReceiveDate = x.record.OfficeReceiveDate,
                        OfficeRemark = x.record.OfficeRemark ?? "暂无",
                        ApplyUserName = x.empoly.EmpolyName,
                        ApplyUserID = x.record.OfficeApplyID  // 使用 OfficeApplyID 作为申请人ID
                    })
                    .ToList();

                return Json(new
                {
                    code = 0,
                    msg = "success",
                    count = totalCount,
                    data = list
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取办公用品列表异常: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                return Json(new { code = 1, msg = "查询失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult GetAvailableAssets()
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser == null)
                {
                    return Json(new { code = 1, msg = "用户未登录" });
                }

                // 查询办公用品类型的资产
                var officeSupplyType = db.AssetTypeInfo
                    .FirstOrDefault(t => t.AssetTypeName.Contains("办公用品"));

                if (officeSupplyType == null)
                {
                    return Json(new { code = 1, msg = "未找到办公用品资产类型" });
                }

                var assets = db.AssetInfo
                    .Where(a => a.AssetTypeID == officeSupplyType.AssetTypeID)
                    .Select(a => new
                    {
                        AssetID = a.AssetID,
                        AssetName = a.AssetName,
                        AssetModel = a.AssetModel
                    })
                    .ToList();

                return Json(new { code = 0, data = assets }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult SubmitApply(int assetId, int applyNum, string applyRemark)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser == null)
                {
                    return Json(new { code = 1, msg = "用户未登录" });
                }

                if (assetId <= 0) return Json(new { code = 1, msg = "请选择正确的资产" });
                if (applyNum <= 0) return Json(new { code = 1, msg = "申请数量必须大于0" });

                // 验证资产是否存在
                var asset = db.AssetInfo.Find(assetId);
                if (asset == null)
                {
                    return Json(new { code = 1, msg = "选择的资产不存在" });
                }

                var newApply = new OfficeSuppliesRecordInfo
                {
                    AssetID = assetId,
                    OfficeApplyNum = applyNum,
                    OfficeApplyState = 0, // 申请中
                    OfficeApplyDate = DateTime.Now,
                    OfficeRemark = applyRemark,
                    OfficeApplyID = currentUser.EmpolyID,  // 使用 OfficeApplyID 存储申请人ID
                    OfficeReceiveNum = null,
                    OfficeReceiveDate = null
                };

                db.OfficeSuppliesRecordInfo.Add(newApply);
                int result = db.SaveChanges();

                if (result > 0)
                {
                    System.Diagnostics.Debug.WriteLine($"申请提交成功，申请ID: {newApply.OfficeID}");
                    return Json(new { code = 0, msg = "申请提交成功，等待管理员审批" });
                }
                else
                {
                    return Json(new { code = 1, msg = "申请提交失败" });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"申请提交异常: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                return Json(new { code = 1, msg = "申请失败：" + ex.Message });
            }
        }

        [HttpPost]
        public JsonResult ApproveApply(int id, bool isAgree, int? receiveNum = null, string approveRemark = "")
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser?.RoleID != 1)
                {
                    return Json(new { code = 1, msg = "没有权限执行审批操作" });
                }

                var applyRecord = db.OfficeSuppliesRecordInfo.Find(id);
                if (applyRecord == null)
                {
                    return Json(new { code = 1, msg = "申请记录不存在" });
                }

                if (applyRecord.OfficeApplyState != 0)
                {
                    return Json(new { code = 1, msg = "该申请已处理，无需重复审批" });
                }

                if (isAgree)
                {
                    if (!receiveNum.HasValue || receiveNum.Value <= 0)
                    {
                        return Json(new { code = 1, msg = "同意申请时必须填写领取数量" });
                    }

                    if (receiveNum.Value > applyRecord.OfficeApplyNum)
                    {
                        return Json(new { code = 1, msg = "领取数量不能超过申请数量" });
                    }

                    applyRecord.OfficeApplyState = 1; // 已同意
                    applyRecord.OfficeReceiveNum = receiveNum.Value;
                    applyRecord.OfficeReceiveDate = DateTime.Now;

                    // 组合申请备注和审批备注
                    var originalRemark = string.IsNullOrEmpty(applyRecord.OfficeRemark) ? "" : applyRecord.OfficeRemark + " | ";
                    applyRecord.OfficeRemark = originalRemark + "【审批通过】" +
                        (string.IsNullOrEmpty(approveRemark) ? "申请已通过" : approveRemark);
                }
                else
                {
                    applyRecord.OfficeApplyState = 2; // 已拒绝
                    // 组合申请备注和审批备注
                    var originalRemark = string.IsNullOrEmpty(applyRecord.OfficeRemark) ? "" : applyRecord.OfficeRemark + " | ";
                    applyRecord.OfficeRemark = originalRemark + "【审批拒绝】" +
                        (string.IsNullOrEmpty(approveRemark) ? "申请未通过" : approveRemark);
                }

                db.SaveChanges();

                string actionText = isAgree ? "同意" : "拒绝";
                return Json(new { code = 0, msg = $"审批成功，已{actionText}该申请" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "审批失败：" + ex.Message });
            }
        }

        private EmpolyInfo GetCurrentUser()
        {
            try
            {
                if (Session["user"] != null)
                {
                    var sessionUser = Session["user"] as EmpolyInfo;
                    if (sessionUser != null && sessionUser.EmpolyID > 0)
                    {
                        var dbUser = db.EmpolyInfo.Find(sessionUser.EmpolyID);
                        if (dbUser != null)
                        {
                            return dbUser;
                        }
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取当前用户异常: {ex.Message}");
                return null;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}